package com.base.threadpool.task.factory;

import com.base.core.utils.SpringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

public class TaskFactoryBuilder {

    /**
     * TokenGranter缓存池
     */
    private static Map<String, TaskFactory> taskPool = new ConcurrentHashMap<>();

    private final static Log log = LogFactory.getLog(TaskFactoryBuilder.class);

    /**
     * 保证可见性和禁止指令重排
     */
    private volatile static TaskFactoryBuilder taskFactoryBuilder;// 缓存实例对象

    private TaskFactoryBuilder() throws Exception {
        this.loadTaskPoolObject();
    }

    public static TaskFactoryBuilder getInstance() throws Exception {
        if(null == taskFactoryBuilder){
            synchronized (TaskFactoryBuilder.class){
                if(null == taskFactoryBuilder){
                    taskFactoryBuilder = new TaskFactoryBuilder();
                }
            }
        }
        return taskFactoryBuilder;
    }

    /**
     * 装载任务池实现对象
     */
    private void loadTaskPoolObject() {
        taskPool = SpringUtils.getBeansOfType(TaskFactory.class);
    }

    /**
     * 获取
     *
     * @param support 实现类名
     * @return ITokenGranter
     */
    public TimerTask getTaskFactory(Object params, String support) throws Exception {
        support = support.replaceFirst(support.substring(0,1),support.substring(0,1).toLowerCase());
        TaskFactory taskFactory = taskPool.get(support);
        if (taskFactory == null) {
            throw new Exception("no support was found");
        }
        return taskFactory.executeTask(params);
    }

}
